window.onload = function() {
    const $ = name => document.querySelector(name);
    var teacherlogo = document.getElementById('teachercentre');
    var un = window.localStorage.getItem('username');
    var role6 = window.localStorage.getItem('role');
    var dropbtn = $('.dropdown');
    if (role6 == 'teacher') {
        teacherlogo.style.display = 'block';
    }
    document.getElementById('userinfo').innerHTML = '用户名' + '&nbsp' + un;
    if (window.localStorage.getItem('avatar')) {
        document.querySelector(".pic img").src = window.localStorage.getItem('avatar');
    }
    //关于cookie注销的函数
    function setCookie(_name, val, expires) {
        var d = new Date();
        d.setDate(d.getDate() + expires);
        document.cookie = _name + "=" + val + ";path=/;expires=" + d.toGMTString();
    }
    //退出登录，返回主页
    function Outlogin() {
        window.localStorage.removeItem("token");
        window.localStorage.removeItem('role');
        window.localStorage.removeItem('id');
        window.localStorage.removeItem('avatar');
        rlogo.style.display = 'none';
        var obj = {};
        obj.name = '';
        obj.pass = '';
        var str = JSON.stringify(obj);
        setCookie("init", str, 0.000001);
    }

    //退出登录
    document.querySelector("#out-login").addEventListener('click', function() {
        Outlogin();
    })
    var token1 = window.localStorage.getItem('token');
    var userinfo = document.getElementById('userinfo');
    axios.defaults.timeout = 5500;
    axios.defaults.baseURL = 'http://120.24.80.83:3000';
    // axios.defaults.headers.common['Authorization'] = token1;
    axios.interceptors.request.use(function(config) {
        // 在发送请求之前做些什么
        // 若token存在， 则在每次请求头中加入token
        if (window.localStorage.getItem('token')) {
            config.headers.Authorization = window.localStorage.getItem('token');
            // axios.defaults.headers.common['Authorization'] = window.localStorage.getItem('token');
        }
        // console.log(config);
        return config;
    }, function(error) {
        // 对请求错误做些什么
        return Promise.reject(error);
    });
    axios.interceptors.response.use(
            response => {
                if (getCookie("init")) {
                    // personBusi();
                    var cookie = JSON.parse(getCookie("init"));
                } else {
                    var cookie = new Object();
                    var cookie = {
                        name: '',
                        pass: ''
                    };
                }
                if (response.data.msg == '登录失效' && (cookie.name == '' && cookie.pass == '')) {
                    // 这里写清除token的代码
                    // 清除token
                    console.log(response.data.msg);
                    setTimeout(() => {
                        // window.open('login.html');
                        rlogo.style.display = 'none';
                        userinfo.style.display = 'none';
                        userinfo.style.height = '0';
                    }, 3000);
                    // window.localStorage.removeItem('token');
                    console.log('登录过期，请重新登录');
                    window.location.assign("/易动考核/拉勾教育/Homepage/index1.html");
                    Message({
                        message: '登录过期，请重新登录',
                        duration: 1000,
                        forbidClick: true
                    });
                    Message();
                    //window.location.href = 'index1.html';
                } else if ((response.data.code == 1 && (cookie.name != '' && cookie.pass != '')) || (response.data.code == 1 && (cookie.name == '' && cookie.pass == ''))) {
                    console.log('登录状态');
                    rlogo.style.display = 'block'
                    userinfo.style.display = 'block';
                }
                return response;
            },
            error => {
                if (error.response) {
                    switch (error.response.status) {
                        case 403:
                            // 这里写清除token的代码
                            console.log('清除token');
                            id1 = '';
                            Message({
                                message: '登录过期，请重新登录',
                                duration: 1000,
                                forbidClick: true
                            });
                            // 清除token
                            window.loaclStorage.removeItem('token');
                            break;
                    }
                }
                return Promise.reject(error.response.data)
            }
        )
        //页面加载时，如果有记录7天免登录
    if (getCookie("init")) {
        var cookie = JSON.parse(getCookie("init"));
        if (cookie.name != '' && cookie.pass != '') {
            axios({
                    url: "/login",
                    method: "post",
                    data: {
                        "username": cookie.name,
                        "password": cookie.pass,
                    }
                })
                .then(function(response) {
                    personBusi();
                    console.log(response.data);
                    var res = response.data.data;
                    //使用loackstorge保存token，方便以后需要的时候用
                    rlogo.style.display = 'block';
                    userinfo.style.display = 'block';
                    dropbtn.style.display = 'inline-block';
                    window.localStorage.removeItem("token");
                    window.localStorage.setItem("token", res.token);
                    document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + res.username;
                    if (res.role == 'teacher') {
                        teacherlogo.style.display = 'block';
                        document.getElementById('rolelogo').innerHTML = '教师';
                    } else if (res.role == 'student') {
                        teacherlogo.style.display = 'none';
                        document.getElementById('rolelogo').innerHTML = '学生';
                    }
                    if (res.avatar) {
                        document.querySelector(".pic img").src = res.avatar;
                    } else {
                        document.querySelector('#rlogo img').src = "img/register.png";
                    }
                })
        } else {
            console.log('cookie已注销');
            window.location.href = "index1.html";
        }
    }
    //封装每隔五分钟发送请求的函数
    function personBusi() {
        var cookie = JSON.parse(getCookie("init"));
        setTimeout(personBusi, 1000 * 60 * 5); //这里的1000表示1秒有1000毫秒,1分钟有60秒,5表示总共5分钟 
        axios({
                url: "/login",
                method: "post",
                data: {
                    "username": cookie.name,
                    "password": cookie.pass,
                }
            })
            .then(response => {
                if (response.data.code == 1) {
                    var res1 = response.data.data;
                    console.log('刷新token');
                    rlogo.style.display = 'block';
                    userinfo.style.display = 'block';
                    dropbtn.style.display = 'inline-block';
                    window.localStorage.removeItem("token");
                    window.localStorage.setItem("token", res1.token);
                    document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + res1.username;
                    if (res1.role == 'teacher') {
                        teacherlogo.style.display = 'block';
                        document.getElementById('rolelogo').innerHTML = '教师';
                    } else if (res1.role == 'student') {
                        teacherlogo.style.display = 'none';
                        document.getElementById('rolelogo').innerHTML = '学生';
                    }
                    if (res1.avatar) {
                        document.querySelector(".pic img").src = res1.avatar;
                    } else {
                        document.querySelector('#rlogo img').src = "img/register.png";
                    }
                }
            })

    }

    function getCookie(_name) {
        var cookie = document.cookie;
        var arr = cookie.split("; ");
        for (var i = 0; i < arr.length; i++) {
            var newArr = arr[i].split("=");
            if (newArr[0] == _name) {
                return newArr[1];
            }
        }
    }
    //验证token是否失效
    if (window.localStorage.getItem("token")) {
        axios({
            method: 'post',
            url: '/refresh',
        }).then(response => {
            var res = response.data;
            console.log(res);
            if (res.code == 1) {
                console.log('token有效');
                var id3 = window.localStorage.getItem('username');
                var role3 = window.localStorage.getItem('role');
                userinfo.style.display = 'block';
                dropbtn.style.display = 'inline-block';
                document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + id3;
                if (role3 == 'teacher') {
                    teacherlogo.style.display = 'block';
                    document.getElementById('rolelogo').innerHTML = '教师';
                } else if (role3 == 'student') {
                    teacherlogo.style.display = 'none';
                    document.getElementById('rolelogo').innerHTML = '学生';
                }
                rlogo.style.display = 'block';
                if (window.localStorage.getItem('avatar')) {
                    document.querySelector(".pic img").src = window.localStorage.getItem('avatar');
                } else {
                    document.querySelector('#rlogo img').src = "img/register.png";
                }
            } else {
                console.log('error');
                // window.location.href = "index1.html";
                // window.location.assign("/易动考核/拉勾教育/Homepage/index1.html");
            }

        }).catch(err => {

        })
    }
    //搜索功能模块
    var search_input = $('.search-input');
    var search_content = $('.search-content');
    var search_box = $('.search');
    search_input.addEventListener('input', function() {
        var value = this.value.replace(/\s/g, '')
        if (value != '') {
            search(value);
        } else {
            clearTimeout(timer);
            $('.search-content').style.display = 'none';
            search_content.innerHTML = '';
        }
    })
    search_input.addEventListener('focus', function() {
        this.style.color = '#333'
    })
    search_input.addEventListener('blur', function() {
        this.style.color = '#999'
        setTimeout(() => {
            search_input.value = '';
        }, 1000);
    })
    search_box.addEventListener('click', function(e) {
        e.stopPropagation()
        var value = search_input.value.replace(/\s/g, '')
        if (value != '') {
            search_content.style.height = '320px';
            $('.search-content').style.display = 'block';
        }
    })
    document.addEventListener('click', function() {
        search_content.style.display = 'none';
    })
    var to_search = $('.to_search');
    to_search.addEventListener('click', function() {
        var value = search_input.value.replace(/\s/g, '');
        if (value != '') {
            window.localStorage.title = value;
            window.location.href = '../Searchcourse/searchcourse.html';
        }
    })
    window.addEventListener('keyup', function(e) {
            if (e.keyCode == 13 && search_input.value != '' && search_input == document.activeElement) {
                to_search.click()
            }
        })
        //利用防抖函数优化搜索课程功能
    var timer = null

    function search(value) {
        clearTimeout(timer)
        timer = setTimeout(function() {
            axios({
                url: '/course/search',
                params: {
                    title: value
                }
            }).then(response => {
                if (response.data.msg == '查找成功') {
                    var data = response.data.data
                    var str = ''
                    for (var k in data) {
                        str +=
                            `<li courseid="` + data[k].id + `">
                       <img src="` + data[k].image + `" alt="">
                       <div class="course-info">
                           <h2 class="course-title">` + data[k].title + `</h2>
                           <div class="teacher-info">
                               <span class="teacher-name">` + data[k].teacherName + `</span>
                               <span class="teacher-work">` + data[k].teacherTitle + `</span>
                           </div>
                       </div>
                   </li>`
                    }
                    search_content.innerHTML = str;
                    var course_titles = search_content.querySelectorAll('.course-title');
                    var course_titles_len = course_titles.length;
                    var teacher_names = document.querySelectorAll('.teacher-name');
                    var teacher_works = document.querySelectorAll('.teacher-work');
                    var reg = new RegExp(value, "g");
                    for (var i = 0; i < course_titles_len; i++) {
                        course_titles[i].innerHTML = course_titles[i].innerHTML.replace(reg, '<span class="highlight">' + value + '</span>')
                        teacher_names[i].innerHTML = teacher_names[i].innerHTML.replace(reg, '<span class="highlight">' + value + '</span>')
                        teacher_works[i].innerHTML = teacher_works[i].innerHTML.replace(reg, '<span class="highlight">' + value + '</span>')
                    }
                    $('.search-content').style.display = 'block';
                }
                console.log(response.data);
                var li1 = document.querySelectorAll('li');
                for (let t = 0; t < li1.length; t++) {
                    li1[t].addEventListener('click', function() {
                        window.localStorage.setItem('courseid', li1[t].getAttribute('courseid'));
                        window.location.href = '../course-details/course-details-two.html';
                    })
                }
            }).catch(err => {
                console.log(err);
            })
            console.log(value)
        }, 800)
    }
    var searchresult = $('.showresult');

    function successtip() {
        var tips = $('.aftertips');
        // all_grandson(after_modify_tips)[1].style.color = '#67c23a'
        // first_son(after_modify_tips).style.backgroundColor = '#f0f9eb'
        tips.style.opacity = '1';
        tips.style.top = '60px';
        tips.style.color = '#67c23a';
        console.log('成功');
        setTimeout(function() {
            tips.style.opacity = '.2';
            tips.style.top = '-60px';
        }, 1800)
    }

    //  操作失败后的提示信息
    function errtip() {
        var tips = $('.aftertips')
        tips.style.opacity = '1';
        tips.style.top = '60px';
        tips.style.color = '#f02019';
        setTimeout(function() {
            tips.style.opacity = '.2';
            tips.style.top = '-60px';
        }, 1800)
    }

    function Ifbuy() {
        axios({
            method: 'post',
            url: '/course/hasBuyCourse',
            data: {
                userId: window.localStorage.getItem('id'),
                courseId: window.localStorage.getItem('courseid')
            }
        }).then(res => {
            console.log(res.data);
            if (res.data.msg == '已经购买了该课程') {
                window.location.href = '../course-details/course-details-three.html';
            } else {
                window.location.assign('../course-details/course-details-two.html');
                console.log('1');
            }
        })
    }
    //渲染已搜索到的课程
    axios({
        method: 'get',
        url: '/course/search',
        params: {
            title: window.localStorage.getItem('title')
        }
    }).then(response => {
        if (response.data.msg == '查找成功') {
            $('.aftertips').innerHTML = '√ 查找成功！';
            successtip();
            var res = response.data.data;
            if (res.length == 0) {
                $('.tipshow').innerHTML = '用尽了洪荒之力也没找到结果！';
            } else {
                $('.tipshow').innerHTML = '来啦来啦，为你找到以下结果！';
            }
            var str = '';
            for (var t in res) {
                if (res[t].originalPrice != null & res[t].originalPrice != '') {
                    str += `  <li courseid="${res[t].id}" class="detail-box">
                <div class="detail-pic ">
                    <img src="${res[t].image}" alt="loading" class="la">
                </div>
                <div class="detail-message ">
                    <p class="message-1 ">
                       ${res[t].title}
                    </p>
                    <p class="message-2 ">
                        ${res[t].brief}
                    </p>
                    <p class="message-3 ">
                        ${res[t].teacherTitle}
                    </p>
                    <div class="service ">
                        <div class="total-price ">
                            <span class="price-money ">￥</span>
                            <span class="price-num ">${res[t].price}</span>
                            <span class="_oldprice">¥${res[t].originalPrice}</span></div>
                            <span class="eight-num-show ">${res[t].pruchasedCount}</span>
                        </div>
                    </div>
                </div>
                </li>`;
                } else {
                    str += ` <li courseid="${res[t].id}" class="detail-box">
                    <div class="detail-pic ">
                        <img src="${res[t].image}" data-src="${res[t].image}" alt="loading" class="la">
                    </div>
                    <div class="detail-message ">
                        <p class="message-1 ">
                           ${res[t].title}
                        </p>
                        <p class="message-2 ">
                            ${res[t].brief}
                        </p>
                        <p class="message-3 ">
                            ${res[t].teacherTitle}
                        </p>
                        <div class="service ">
                            <div class="total-price ">
                                <span class="price-money ">￥</span>
                                <span class="price-num ">${res[t].price}</span>
                                <span class="eight-num-show ">${res[t].pruchasedCount}</span>
                            </div>
                        </div>
                    </div>
                    </li>`;
                }
            }
            searchresult.innerHTML = str;
            searchresult.innerHTML += `<div class="detail-box " id="last-detail-box " style="opacity:0;"></div>`;
            var li2 = document.querySelectorAll('.detail-box');
            // console.log(li2);
            for (let t = 0; t < li2.length; t++) {
                li2[t].addEventListener('click', function() {
                    window.localStorage.setItem('courseid', li2[t].getAttribute('courseid'));
                    Ifbuy();
                })
            }
        }
    })
}